<script setup lang="ts">
import { computed, ref } from "vue";
const idx = ref<number>(0);

export interface Props {
  items?: { label: string }[];
}
const props = withDefaults(defineProps<Props>(), {
  items: () => [],
});

const tabTtems = ref<any>([]);
const emit = defineEmits(["change"]);
const handleClick = (item: any, index: number) => {
  idx.value = index;
  emit("change", idx.value);
};
const percent = computed(() => {
  return tabTtems.value
    .slice(0, idx.value)
    .reduce((pre: any, cur: any) => pre + cur.clientWidth, 0);
});
const clientWidth = computed(() => {
  return Number(tabTtems.value[idx.value]?.clientWidth);
});
</script>

<template>
  <div class="tabs">
    <div class="pb-10px tab-item-container">
      <div
        class="tab-item"
        @click="handleClick(item, index)"
        v-for="(item, index) in items"
        :key="index"
        ref="tabTtems"
      >
        <span>{{ item.label }}</span>
      </div>

      <div class="progress-bg"></div>
      <div class="progress">
        <div
          :style="{
            '--percent': percent + 'px',
            '--clientWidth': clientWidth - 50 + 'px',
          }"
          class="tip"
        ></div>
      </div>
    </div>

    <div class="flex-1">
      <slot></slot>
    </div>
  </div>
</template>

<style scoped lang="less">
.tabs {
  display: flex;
  flex-direction: column;
  margin: auto;
  .tab-item-container {
    position: relative;
    white-space: nowrap;
    overflow-x: auto;
  }
  .tab-item-container::-webkit-scrollbar {
    display: none; /* 隐藏滚动条 */
  }
  .tab-item {
    display: inline-block;
    padding: 5px 20px;
    cursor: pointer;
    &:hover {
      color: #409eff;
    }
    &.active {
      position: relative;
      &::after {
        content: "";
        position: absolute;
        bottom: 0;
        left: 0;
        transform: translateX(50%);
        width: 50%;
        height: 2px;
        background: #409eff;
        transition: all 0.3s;
      }
    }
  }
}
.progress-bg {
  height: 2px;
  border-radius: 4px;
  background: #e4e7ed;
  position: absolute;
  left: 0;
  right: 0;
  z-index: -1;
}
.progress {
  width: 100%;
  border-radius: 4px;
  position: relative;
  z-index: -1;
  .tip {
    position: absolute;
    width: var(--clientWidth);
    height: 2px;
    left: 24px;
    transform: translateX(var(--percent));
    background-color: #409eff;
    border-radius: 4px;
    transition: all 0.3s;
  }
}
</style>
